<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

class Gupiao extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    //更新fa_stock_base url 不区分大小写
    //http://gupiao.test/api/gupiao/updatestockbase
    public function updatestockbase()
    {
        $list = Model("\app\admin\model\stock\Base")
            ->field('id, code')
            ->select();

        $this->setMA($list);
        $this->success('返回成功', 'MMM');

        foreach ($list as $s) {
            echo $s['code'] . '-' . $s->id . '<br>';
            $stock = \app\admin\model\stock\Base::get($s->id);
            $stock->YU5 = $stock->LU5;
            $stock->YU10 = $stock->LU10;
            $stock->YU20 = $stock->LU20;
            $stock->YU30 = $stock->LU30;
            $stock->YU89 = $stock->LU89;
            $stock->YU250 = $stock->LU250;

            $klist = Model("\app\admin\model\stock\K")
                ->where("code=" . $s['code'])
                ->order('id desc')
                ->select();
            $index = 0;
            $MA = 0;
            $volume = 0;
            foreach ($klist as $k) {
                $MA += $k->close;
                $volume += $k->volume;
                if ($index == 0) {
                    $stock->MA1 = $k->close;
                    $stock->peTTM = $k->peTTM;
                    $stock->pctChg = $k->pctChg;
                    $stock->volume = $k->volume;
                    $stock->pctChg = $k->pctChg;
                    $volume = 0;
                } else if ($index == 4) {
                    $stock->MA5 = $MA / 5;
                } else if ($index == 9) {
                    $stock->MA10 = $MA / 10;
                } else if ($index == 19) {
                    $stock->MA20 = $MA / 20;
                } else if ($index == 29) {
                    $stock->MA30 = $MA / 30;
                } else if ($index == 88) {
                    $stock->MA89 = $MA / 89;
                } else if ($index == 249) {
                    $stock->MA250 = $MA / 250;
                } else if ($index == 2) {
                    $stock->pctChg3 = $stock->MA1 - $k->close;
                } else if ($index == 5) {
                    $stock->pctChg6 = $stock->MA1 - $k->close;
                } else if ($index == 3) {
                    $stock->volume3 = $volume / 3;//前3日平均成交量 -- 看今日是否是增量
                } else if ($index == 6) {
                    $stock->volume6 = $volume / 6;
                }
                $index++;
            }

            // 股价偏离20日均线的尺子
            $stock->X20 = $stock->MA1 / $stock->MA20;

            $stock->LU5 = 0;
            $stock->LU10 = 0;
            $stock->LU20 = 0;
            $stock->LU30 = 0;
            $stock->LU89 = 0;
            $stock->LU250 = 0;

            //无法算只有把均线值 放在fa_stock_k里，才可以
//            if ($stock->MA5 > 0) {
//                //连续方向判断， 正-涨 负-跌
//                $D5 = $stock->MA1 - $stock->MA5;
//                $D10 = $stock->MA1 - $stock->MA5;
//                $D20 = $stock->MA1 - $stock->MA5;
//                $D30 = $stock->MA1 - $stock->MA5;
//                $D89 = $stock->MA1 - $stock->MA5;
//                $D250 = $stock->MA1 - $stock->MA5;
//                $index = 0;
//                foreach ($klist as $k) {
//                    if ($D5 > 0 && $k->close > $stock->MA5) {
//
//                    }
//
//                    $index++;
//                }
//
//            }


            if ($stock->H5 > 0) {
                $stock->B5 = ($stock->MA1 - $stock->H5) / $stock->H5;
            }
            if ($stock->H10 > 0) {
                $stock->B5 = ($stock->MA1 - $stock->H10) / $stock->H10;
            }

            $stock->save();
            break;
        }


        $this->success('返回成功', 'dd');
    }

    //超时动作（>30）不能使用webapi执行
    //设置fa_stock_k 均线值
    function setMA($list)
    {
        if (empty($list)) {
            return;
        }

        $num = 0;
        foreach ($list as $s) {
            $klist = Model("\app\admin\model\stock\K")
                ->where("code = '" . $s['code'] . "'")
                ->order('id desc')
                ->select();

            foreach ($klist as $k) {
                if ($k->MA5 > 0) {
                    break;
                }

                $kmodel = \app\admin\model\stock\K::get($k->id);
                $index = 0;
                $MA = 0;
                foreach ($klist as $kk) {
                    if ($kk->id > $k->id) {
                        //5日均线包括今天的
                        continue;
                    }
                    $MA += $kk->close;
                    if ($index == 4) {
                        $kmodel->MA5 = $MA / 5;
                    } else if ($index == 9) {
                        $kmodel->MA10 = $MA / 10;
                    } else if ($index == 19) {
                        $kmodel->MA20 = $MA / 20;
                    } else if ($index == 29) {
                        $kmodel->MA30 = $MA / 30;
                    } else if ($index == 88) {
                        $kmodel->MA89 = $MA / 89;
                    } else if ($index == 249) {
                        $kmodel->MA250 = $MA / 250;
                        break;
                    }
                    $index++;
                }
                $kmodel->save();
                $num++;
            }

            sleep(1);
            echo $s['id'] . '-' . $s['code'] . " ";
            ob_flush();
            flush();
        }
    }


    //http://gupiao.test/api/gupiao/recommend?date=2018-10-10
    public function recommend()
    {
        $date = $this->request->request('date');
        if (empty($date)) {
            $klist = collection(Model("\app\admin\model\stock\K")
                ->field('date')
                ->order('id desc')
                ->limit(1)
                ->select())->toArray();
            foreach ($klist as $k) {
                $date = $k['date'];
                break;
            }
        }
        echo $date . "\t\r";

//        SELECT code from fa_stock_k where date = '2019-05-10' and LU5 =1 and LU20 > 0 and LU89 > 0 and B5>3  limit 100

        echo "123\t\r";//在文本里需要这样输入，还必需是双引号
//        echo "<br>";//在html里面才有用
        echo "abc\t\r";

        $this->success('返回成功', 'MMM');// 注销后就成html了
    }

    //获取数据库最新数据的日期
    function getthisdate()
    {
        $klist = collection(Model("\app\admin\model\stock\Hsl")
            ->field('date')
            ->order('id desc')
            ->limit(1)
            ->select())->toArray();
        foreach ($klist as $k) {
            return $k['date'];
        }
    }

    //打印该股票后几天的数据
    function echofuturedata($k)
    {
        if (empty($k)) {
            return;
        }
        $klist2 = collection(Model("\app\admin\model\stock\K")
            ->field('close, date')
            ->where("code= '" . $k['code'] . "' and id > " . $k['id'])
            ->limit(10)
            ->select())->toArray();
        if (!empty($klist2)) {
            $i = 0;
            foreach ($klist2 as $k2) {
                $i++;
                if ($i < 4 || $i == 6 || $i == 10) {
                    $x = (floatval($k2['close']) - floatval($k['close'])) / floatval($k['close']) * 100;
                    echo "[" . $i . "]" . $k2['date'] . "&nbsp;&nbsp;" . sprintf("%.2f", substr(sprintf("%.3f", $x), 0, -2)) . "% &nbsp;&nbsp;&nbsp;";
                }
            }
        }
        echo "<br>";
    }

    //获取前一个交易日的数据
    function getpredata($k)
    {
        if (empty($k)) {
            return null;
        }
        $klist2 = collection(Model("\app\admin\model\stock\K")
            ->where("code= '" . $k['code'] . "' and id < " . $k['id'])
            ->order('id desc')
            ->limit(1)
            ->select())->toArray();
        if (!empty($klist2)) {
            foreach ($klist2 as $k2) {
                return $k2;
            }
        }
        return null;
    }

    //http://gupiao.test/api/gupiao/geini_a?date=2018-10-10
    public function geini_a()
    {
        echo "例子：http://apiccr.megowx.com:88/api/gupiao/geini_a?date=2018-10-10 <br>";

        $date = $this->request->request('date');
        if (empty($date)) {
            $date = $this->getthisdate();
        }
        echo "采用 " . $date . " K线数据的推荐：<br>短线推荐：<br>1. 绩优股上升通道回踩：<br>";

//        SELECT code from fa_stock_k where date = '2019-05-10' and LU5 =1 and LU20 > 0 and LU89 > 0 and B5>3  limit 100
        $klist = Model("\app\admin\model\stock\K")
            ->field('id, code, close')
            ->where("date= '" . $date . "' and LU5 = 1 and LU20 > 0 and LU89 > 0 and B5 > 3")
            ->order('code asc')
            ->limit(100)
            ->select();

        foreach ($klist as $k) {
            echo $k->code . "&nbsp;&nbsp;--- &nbsp;&nbsp;" . intval($k->close) . "&nbsp;&nbsp;";
            $this->echofuturedata($k);
        }

        echo "<br>中长线推荐：<br> 1. 绩优股：<br>";
        $klist = Model("\app\admin\model\stock\K")
            ->field('id, code, close')
            ->where("date= '" . $date . "' and LU89 = 1 and LU5 > 0 and LU20 > 0 and B5 >= 3")
            ->order('code asc')
            ->limit(100)
            ->select();

        foreach ($klist as $k) {
            echo $k->code . "&nbsp;&nbsp;--- &nbsp;&nbsp;" . intval($k->close) . "&nbsp;&nbsp;";
            $this->echofuturedata($k);
        }

        echo "2. 非绩优股：<br>";
        $klist = Model("\app\admin\model\stock\K")
            ->field('id, code, close')
            ->where("date= '" . $date . "' and LU89 = 1 and LU5 > 0 and LU20 > 0  and B5 < 3")
            ->order('code asc')
            ->limit(100)
            ->select();

        foreach ($klist as $k) {
            echo $k->code . "&nbsp;&nbsp;--- &nbsp;&nbsp;" . intval($k->close) . "&nbsp;&nbsp;";
            $this->echofuturedata($k);
        }


    }

    //http://gupiao.test/api/gupiao/geini_b?date=2018-10-10&code=sh.000001
    public function geini_b()
    {
        echo "例子：http://apiccr.megowx.com:88/api/gupiao/geini_b?code=sh.600248&date=2015-07-08 <br>";
        $code = $this->request->request('code');
        $date = $this->request->request('date');
        if (empty($date)) {
            $date = $this->getthisdate();
        }

        if (empty($code)) {
            $code = "sh.000001";
        }
        echo $date . "&nbsp;&nbsp;" . $code . "&nbsp;&nbsp;--- 超跌？ or 超涨？：<br>";
//        select code, date from fa_stock_k WHERE code = 'sh.000001' and date = '2019-05-13'
        $where = "code= '" . $code . "' and date='" . $date . "' ";
        $klist0 = collection(Model("\app\admin\model\stock\K")
            ->field('id, code, close, date, X20')
            ->where($where)
            ->limit(1)
            ->select())->toArray();

        $x20 = 0;
        if ($klist0) {
            foreach ($klist0 as $k0) {
                $x20 = floatval($k0['X20']);
                echo $k0['code'] . "&nbsp;--- &nbsp;" . $k0['date'] . "&nbsp;" . floatval($k0['close']) . "&nbsp;" . $x20 . "<br><br>";
                break;
            }
        }

        $jielun = 0;
        echo "超跌记录：<br>";
        $klist1 = collection(Model("\app\admin\model\stock\K")
            ->field('id, code, close, date, X20')
            ->where("code= '" . $code . "' and X20 <> 0")
            ->order('X20')
            ->limit(30)
            ->select())->toArray();

        $i = 0;
        foreach ($klist1 as $k1) {
            $i++;
            if ($date == $k1['date']) {
                $jielun = $i;
                echo "***";
            }
            echo $k1['date'] . "&nbsp;--- &nbsp;" . substr($k1['X20'], 0, 8) . "&nbsp;&nbsp;|&nbsp;&nbsp;";
            $this->echofuturedata($k1);
        }

        echo "<br>超涨记录：<br>";
        $klist1 = collection(Model("\app\admin\model\stock\K")
            ->field('id, code, close, date, X20')
            ->where("code= '" . $code . "' and X20 <> 0")
            ->order('X20 desc')
            ->limit(30)
            ->select())->toArray();

        $i = 0;
        foreach ($klist1 as $k1) {
            $i++;
            if ($date == $k1['date']) {
                $jielun = $i;
                echo "***";
            }
            echo $k1['date'] . "&nbsp;--- &nbsp;" . substr($k1['X20'], 0, 8) . "&nbsp;&nbsp;|&nbsp;&nbsp;";
            $this->echofuturedata($k1);
        }

        echo "<br>结论：(当日除权股此结论无效)<br>";

        if ($x20 > 1) {
            if ($jielun > 0) {
                echo "已超涨，除非一字涨停，建议做反T！如未跌横盘几日，可能会继续上涨。";
            } else {
                echo "放量上涨可以继续持股！";
            }
        } else if ($x20 < 1) {
            if ($jielun > 0) {
                if ($jielun < 13) {
                    echo "已严重超跌，除非一字跌停，可以建仓！";
                } else {
                    echo "已超跌，可在日均线下分批进入！";
                }
                echo "<br>超跌3日未反弹，横盘接近20均线，则撤离！";
            } else {
                echo "还有下跌的空间！";
            }
        }
        echo "<br><br><br>";

    }

    //http://gupiao.test/api/gupiao/geini_c?date=2018-10-10
    //http://apiccr.megowx.com:88/api/gupiao/geini_c?date=2018-10-10
    public function geini_c()
    {
        echo "例子：apiccr.megowx.com:88/api/gupiao/geini_c?date=2018-10-10 <br>";
        $date = $this->request->request('date');
        if (empty($date)) {
            $date = $this->getthisdate();
        }

        echo "采用 " . $date . " K线数据的超跌股推荐：(*为绩优股)<br>";
        echo "[x] 表示历史低位, x > 20 还需观望<br><br>";

        $klist = collection(Model("\app\admin\model\stock\K")
            ->field('id, code, close, X20, B5')
            ->where("date= '" . $date . "' and X20 > 0.6 and X20 < 0.85 and isST='0' ")
            ->order('X20')
            ->limit(60)
            ->select())->toArray();

        foreach ($klist as $k) {
            $where = "code= '" . $k['code'] . "' and id < " . $k['id'] . " and X20 < " . $k['X20'];
            $total = Model("\app\admin\model\stock\K")
                ->where($where)
                ->count();

            if ($total > 30) {
                continue;
            }

            if (floatval($k['B5']) > 3) {
                echo "(*)";
            }

            echo $k['code'] . "&nbsp;&nbsp;--- &nbsp;&nbsp;" . intval($k['close']) . "[" . $total . "]&nbsp;&nbsp;";
            $this->echofuturedata($k);
        }
    }

    //http://gupiao.test/api/gupiao/geini_d?date=2018-10-10
    //http://apiccr.megowx.com:88/api/gupiao/geini_d?date=2018-10-10
    public function geini_d()
    {
        echo "例子：http://apiccr.megowx.com:88/api/gupiao/geini_d?date=2018-10-10 <br>";

        $date = $this->request->request('date');
        if (empty($date)) {
            $date = $this->getthisdate();
        }
        echo "采用 " . $date . " K线数据的推荐：<br>长线推荐：<br>";

        $klist = collection(Model("\app\admin\model\stock\K")
            ->field('id, date, code, close, LU89')
            ->where("date= '" . $date . "' and LU89 = 1")
            ->order('code asc')
            ->select())->toArray();

        foreach ($klist as $k) {
            $k2 = $this->getpredata($k);
            if (empty($k2))
                continue;
//            if (intval($k2['LU89']) > -100) {
//                continue;
//            }
            $lux = $k['LU89'] - $k2['LU89'];
            if ($lux < 100) {
                continue;
            }
            echo $k['code'] . "&nbsp;&nbsp;--- &nbsp;&nbsp;" . intval($k['close']) . "&nbsp;&nbsp;";
            $this->echofuturedata($k);
        }
    }

    //http://gupiao.test/api/gupiao/geini_e?date=2018-10-10
    //http://apiccr.megowx.com:88/api/gupiao/geini_e?date=2018-10-10
    public function geini_e()
    {
        echo "例子：http://apiccr.megowx.com:88/api/gupiao/geini_e?date=2018-10-10 <br>";

        $date = $this->request->request('date');
        if (empty($date)) {
            $date = $this->getthisdate();
        }
        echo "采用 " . $date . " K线数据的推荐->接近20日均线,30日均线强支撑：<br>";
        echo "1.绩优股：<br>";
        $where = "date= '" . $date . "' and X20 > 0.99 and X20 < 1.06 and LU30 > 15 and B5 > 3";
        echo $where . "<br><br>";

        $klist = collection(Model("\app\admin\model\stock\K")
            ->field('id, date, code, close, X20')
            ->where($where)
            ->order('code asc')
            ->select())->toArray();

        foreach ($klist as $k) {
            echo $k['code'] . "&nbsp;&nbsp;--- &nbsp;&nbsp;" . intval($k['close']) . "&nbsp;&nbsp;" . $k['X20'];
            $this->echofuturedata($k);
        }

        echo "<br>2.非绩优股, 低价格 < 5元：<br>";
        $where0 = " and isST='0' and tradestatus = '1'";//公共条件
        $where = "date= '" . $date . "' and X20 > 0.99 and X20 < 1.06 and LU30 > 15 and close < 5 " . $where0;
        echo $where . "<br><br>";

        $klist = collection(Model("\app\admin\model\stock\K")
            ->field('id, date, code, close, X20')
            ->where($where)
            ->order('code asc')
            ->select())->toArray();

        foreach ($klist as $k) {
            echo $k['code'] . "&nbsp;&nbsp;--- &nbsp;&nbsp;" . intval($k['close']) . "&nbsp;&nbsp;" . $k['X20'];
            $this->echofuturedata($k);
        }
    }

    //http://gupiao.test/api/gupiao/geini_f?code=sz.300773
    //http://apiccr.megowx.com:88/api/gupiao/geini_f?code=sz.300773
    public function geini_f()
    {
        $code = $this->request->request('code');

        $klist = collection(Model("\app\admin\model\stock\K")
            ->where("code = '" . $code . "'")
            ->field('date, open, close, low, high')
            ->limit(10)
            ->select())->toArray();

//        echo "<br>" . json_encode($klist);

        $klist2 = [];
        foreach ($klist as $k) {
//            019-04-25
            $klist2[] = array(
                str_replace("-", "/", $k['date']),
                floatval($k['open']),
                floatval($k['close']),
                floatval($k['low']),
                floatval($k['high'])
            );
        }
        echo "<br>" . json_encode($klist2);

        //当日成本线
        $dflist = collection(Model("\app\admin\model\stock\Dfk")
            ->where("code = '" . $code . "'")
            ->order('id desc')
            ->limit(1)
            ->select())->toArray();

        $df = array("", "", "", "");

        foreach ($dflist as $d) {
            $df = array(
                $d['date'],
                "机构参与度" . $d['jgcy'] . "% 主力" . $d['kpflag'],
                "主力净流入" . $d['zlr'] . " 超大单流入" . $d['clr'],
                "1日主力成本" . $d['zc1'] . " 超大单流入" . $d['zc20']
            );
            break;
        }
        echo "<br>" . json_encode($df);
    }


    //http://gupiao.test/api/gupiao/geini_h?date=2018-10-10&code=002464
    //找地量
    public function geini_h()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限

        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $data0 = date('H:i:s');

        $date = $this->request->request('date', '2018-10-10');
        $code = $this->request->request('code', '');

        echo $code . '<br>';

        $where = "code like '%{$code}' and cast(turn as decimal(10,4)) > 0
and (cast(pctChg as decimal(10,4)) > -4 and cast(pctChg as decimal(10,4)) < 4)
and date > '{$date}'";

        $sql = "SELECT id, date, code, close, pctChg, turn FROM `fa_stock_hsl` WHERE  {$where} ORDER BY cast(turn as decimal(10,4)) ASC limit 10 ";
        $klist = \app\admin\model\stock\Hsl::query($sql);

        foreach ($klist as $k) {
            echo $k['date'] . "----" . $k['turn'] . "&nbsp;&nbsp;";
            $this->echofuturedata2($k);
        }

        echo '<br>' . $data0 . ' ~ ' . date('H:i:s') . '<br>';

    }

    //http://gupiao.test/api/gupiao/geini_max?date=2018-10-10&code=002464
    //找天量
    public function geini_max()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限

        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $data0 = date('H:i:s');

        $date = $this->request->request('date', '2018-10-10');
        $code = $this->request->request('code', '');

        $where = "code like '%{$code}' and cast(turn as decimal(10,4)) > 0
and (cast(pctChg as decimal(10,4)) > -9 and cast(pctChg as decimal(10,4)) < 9)
and date > '{$date}'";

        $sql = "SELECT id, date, code, close, pctChg, turn FROM `fa_stock_hsl` WHERE  {$where} ORDER BY cast(turn as decimal(10,4)) DESC limit 10 ";
        $klist = \app\admin\model\stock\Hsl::query($sql);

        foreach ($klist as $k) {
            echo $k['date'] . "----" . $k['turn'] . "&nbsp;&nbsp;";
            $this->echofuturedata2($k);
        }

        echo '<br>' . $data0 . ' ~ ' . date('H:i:s') . '<br>';

    }


    //打印该股票60天内最高价的差值
    function echofuturedata2($k)
    {
        if (empty($k)) {
            return;
        }
        $fromid = intval($k['id']);
        $toid = $fromid + 60;
        $hsl = \app\admin\model\stock\Hsl::query("SELECT * FROM `fa_stock_hsl` WHERE  (  code= '{$k['code']}' and id > {$fromid} and id < {$toid}  ) ORDER BY cast(close as decimal(10,4)) DESC limit 1 ");

        if ($hsl && is_array($hsl)) {
            $hsl = $hsl[0];
            $i = intval($hsl['id']) - $fromid;
            $x = (floatval($hsl['close']) - floatval($k['close'])) / floatval($k['close']) * 100;
            if ($x < 6) {
                $a = 0;
            }
            echo "[" . $i . "]&nbsp;" . $hsl['date'] . "&nbsp;&nbsp;" . sprintf("%.2f", substr(sprintf("%.3f", $x), 0, -2)) . "% <br>";
        } else {
            echo "最新<br>";
        }

    }

    //http://gupiao.test/api/gupiao/geini_t?date=2020-04-20
    //先用python 查询换手率10低.py -- 查找两年内，倒数第10低的换手率
    //地量股今日推荐
    public function geini_t()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限
        $data0 = date('H:i:s');

        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $date = $this->request->request('date', '');
        $date0 = $this->getthisdate();//最新的日期
        $islast = true;
        if (empty($date)) {
            $date = $date0;//最新的日期
            $islast = false;
        }
        $date1 = $date;

        //涨幅在-3～3 turn>0  -- 去掉停牌
        $where = " cast(turn as decimal(10,4)) > 0 and (cast(pctChg as decimal(10,4)) > -3 and cast(pctChg as decimal(10,4)) < 3) ";
        $num = 1;

        while (true) {
            $list = \app\admin\model\stock\Hsl::where("date", $date1)
                ->where($where)
                ->select();

            foreach ($list as $t) {
                $hslyear = \app\admin\model\stock\Hslyear::where('code', $t->code)->find();
                if ($hslyear) {
                    if (floatval($hslyear['turn']) > floatval($t['turn'])) {
                        //
                        $profit = \app\admin\model\stock\Profit::where("code", $t->code)->order('id desc')->limit(1)->find();
                        $profitinfo = "";
                        if ($profit) {
                            $roeAvg = floatval($profit->roeAvg) * 100;
                            $gpMargin = floatval($profit->gpMargin) * 100;
                            $profitinfo = "ROE:{$roeAvg}     毛利率:{$gpMargin}  净利润/营业总收入:{$profit->dupontNitogr}";
                            if ($roeAvg < 20) {
//                                continue;
                            }
                        } else {
//                        continue;
                        }

                        //
                        $strX = "";
                        if ($islast) {
                            $hsl0 = \app\admin\model\stock\Hsl::where("date", $date0)->where("code", $t->code)->find();
                            if ($hsl0) {
                                $x = (floatval($hsl0['close']) - floatval($t['close'])) / floatval($t['close']) * 100;
                                $strX = "涨幅：" . sprintf("%.2f", substr(sprintf("%.3f", $x), 0, -2)) . "%";
                            }

                            if ($x < 30) {
//                                continue;
                            }
                        }

                        echo "{$num}. [{$date1}] {$t['code']} 换手率：{$t['turn']} ---- {$strX}  {$profitinfo} <br>";
                        $num++;
                    }
                }
//            echo $t['code'] . "&nbsp;&nbsp;{$num}<br>";
            }

            if ($date1 == $date0) {
                break;
            }

            $date1 = date("Y-m-d", strtotime($date1 . " +1 day"));
        }


        echo '<br> 查询结束' . $data0 . ' ~ ' . date('H:i:s') . '<br>';

    }

    //http://gupiao.test/api/gupiao/geini_yg?date=2020-04-20
    //妖股遍历 for 日期
    // SELECT * FROM `fa_stock_zf` WHERE  1 ORDER BY cast(zf as decimal(10,4)) DESC
    // SELECT * FROM `fa_stock_zf` WHERE  1 ORDER BY cast(zf as decimal(10,4)) ASC
    public function geini_yg()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限
        $data0 = date('H:i:s');

        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $date = $this->request->request('date', '2018-01-20');//默认两年内
        $list = \app\admin\model\stock\Hslyear::all();

        foreach ($list as $t) {
            $hsllist = \app\admin\model\stock\Hsl::query("SELECT MAX(cast(close as decimal(10,4)))/MIN(cast(close as decimal(10,4))) as zf FROM fa_stock_hsl where code = '{$t['code']}' and date > '{$date}' ");

            if ($hsllist && is_array($hsllist)) {
                $zfmodel = new \app\admin\model\stock\Zf;
                $zfmodel->code = $t['code'];
                $zfmodel->zf = $hsllist[0]['zf'];
                $zfmodel->save();
            }
//            break;
        }

        echo '<br> 搜索结束' . $data0 . ' ~ ' . date('H:i:s') . '<br>';

    }

    //http://gupiao.test/api/gupiao/geini_pyg?date=2020-04-20
    //打印妖股
    // SELECT MAX(cast(close as decimal(10,4))) as zf FROM fa_stock_hsl where code = 'sh.600776' and date > '2018-01-20'
    public function geini_pyg()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限
        $data0 = date('H:i:s');

        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $date = $this->request->request('date', '2018-01-20');//默认两年内
        $list = \app\admin\model\stock\Hslyear::all();
        $num = 0;
        foreach ($list as $t) {
            $hsllist = \app\admin\model\stock\Hsl::query("SELECT MAX(cast(close as decimal(10,4)))/MIN(cast(close as decimal(10,4))) as zf FROM fa_stock_hsl where code = '{$t['code']}' and date > '{$date}' ");
            if ($hsllist && is_array($hsllist) && floatval($hsllist[0]['zf']) > 5) {
                $hsl0 = \app\admin\model\stock\Hsl::where("date > '{$date}' and code = '{$t['code']}'")->order('id asc')->limit(1)->find();
                $hslt = \app\admin\model\stock\Hsl::where("date > '{$date}' and code = '{$t['code']}'")->order('id desc')->limit(1)->find();
                if (floatval($hsl0->close) < floatval($hslt->close)) {
                    $num++;
                    echo $num . ". " . $t['code'] . ' ' . $hsllist[0]['zf'] . '<br>';
//                    break;
                }
            }
        }

        echo '<br> 搜索结束' . $data0 . ' ~ ' . date('H:i:s') . '<br>';

    }


    //http://gupiao.test/api/gupiao/geini_zts?date=2019-04-20&code=300249
    //select * from fa_stock_hsl where code like '%002464' and date > '2018-01-20' and cast(pctChg as decimal(10,4)) > 9.9
    //个股统计涨停数
    public function geini_zts()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限

        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $date = $this->request->request('date', '2018-01-20');//默认两年内
        $code = $this->request->request('code', '');

        $where = "code like '%{$code}' and date > '{$date}' and iszt=1";
        $total = \app\admin\model\stock\Hsl::where($where)->count();

        echo $date . " " . $code . " " . $total;

        echo '<br> 搜索结束' . ' ~ ' . date('H:i:s') . '<br>';

    }

    //http://gupiao.test/api/gupiao/geini_ztsall?date=2019-12-20
    //所有股统计涨停数-6个月内的统计比较有意义
    public function geini_ztsall()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限

        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $date = $this->request->request('date', '2019-12-20');//默认两年内
        $list = \app\admin\model\stock\Hslyear::all();

        echo $date . '<br>';
        $num = 0;
        foreach ($list as $t) {
            $where = "code = '{$t['code']}' and date > '{$date}' and iszt=1";
            $total = \app\admin\model\stock\Hsl::where($where)->count();

            if (intval($total) > 5) {
                $num++;
                echo $num . ". " . $t['code'] . " " . $total . '<br>';
            }

        }

        echo '<br> 搜索结束' . date('H:i:s') . '<br>';

    }



    //统计今年的研报数
    //http://gupiao.test/api/gupiao/tjyb?date=2020-01-01
    public function tjyb()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限

        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $date = $this->request->request('date', '1900-01-01');

        $list = \app\admin\model\stock\Cgje::all();

        foreach ($list as &$t) {
            $code = substr($t->code, 3);
            $t->yba = \app\admin\model\stock\Yb::where("stockCode", $code)->count();
            $yblist = \app\admin\model\stock\Yb::where("publishDate", '>', $date)
                ->where("stockCode", $code)
                ->field("publishDate,stockCode,stockName")
                ->select();
            $t->yb = 0;
            if ($yblist) {
                foreach ($yblist as $y) {
                    $t->stockName = $y->stockName;
                    break;
                }

                $t->yb = count($yblist);
            }

            $t->save();
        }

        echo '<br> 研报数统计结束' . '<br>';

    }

    //今年的研报数 > 10 入股票池
    //http://gupiao.test/api/gupiao/ybtocgje
    public function ybtocgje()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限

        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $sql = "select count(*) as num, stockCode, stockName from fa_stock_yb where publishDate > '2020-01-01' group by stockCode, stockName";
        $list = Db::query($sql);

        foreach ($list as $t) {
            if ($t['num'] < 9) {
                continue;
            }
            $cgje = new \app\admin\model\stock\Cgje;
            if (strpos($t['stockCode'], '3') === 0 || strpos($t['stockCode'], '0') === 0) {
                $cgje->code = "sz.".$t['stockCode'];
            } else {
                $cgje->code = "sh.".$t['stockCode'];
            }
            $cgje->stockName = $t['stockName'];
            $cgje->save();
        }

        echo '<br> 研报加入fa_stock_cgje' . '<br>';

    }

    //统计研报后在此基础上，选择
    //今年研报数 > 10 && 人均持股金额 > 60
    // select * from fa_stock_cgje where yb > 20 and cgje > 90
    //http://gupiao.test/api/gupiao/geini_real?date=2020-08-02
    public function geini_real()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限

        $date = $this->request->request('date', '');
        if (empty($date)) {
            $date = $this->getthisdate();//最新的日期
        }

        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $list = \app\admin\model\stock\Cgje::where("yb", ">", 20)
            ->where("cgje", ">", 90)
            ->select();

        foreach ($list as $t) {
            $k = \app\admin\model\stock\K::where("code", $t->code)->order("id desc")->find();
            //close和MA89的比值
            if (!$k) {
                continue;
            }
            $t->b89 = intval($k->close / $k->MA89 * 100);
            $t->b20 = intval($k->close / $k->MA20 * 100);

            $h = \app\admin\model\stock\Hsl::where("code", $t->code)->order("id desc")->find();
            $y = \app\admin\model\stock\Hslyear::where("code", $t->code)->find();
            if ($h && $y) {
                $t->bhs = intval($h->turn / $y->turn * 100);
            }

            $t->save();
//            echo '<br>' . $t->stockName . ' close=' . $k->close . ' MA89=' . $k->MA89 . '<br>';
        }


        echo '<br> 推荐结束' . date('H:i:s') . '<br>';

    }
    //select * from fa_stock_cgje where yb > 20 and cgje > 90  order by b89 asc


    //列举股票池里股票100日以内的最低换手率
    //http://gupiao.test/api/gupiao/diliang?stardate=2020-01-02
    public function diliang()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限

        $stardate = $this->request->request('stardate', date("Y-m-d", strtotime("-100 day")));

        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $list = \app\admin\model\stock\Cgje::where("yb", ">", 20)
            ->where("cgje", ">", 90)
            ->select();

        foreach ($list as $t) {
            $sql = "SELECT id, date, turn FROM `fa_stock_hsl` WHERE  code = '{$t->code}'  and date >  '{$stardate}' ORDER BY cast(turn as decimal(10,4)) ASC limit 10 ";
            $h = \app\admin\model\stock\Hsl::query($sql);

            if ($h) {
                echo '<br>' . $t->stockName . ' ' . $h[0]['date'];
            }

        }


        echo '<br> 推荐结束' . date('H:i:s') . '<br>';

    }


    //http://gupiao.test/api/gupiao/testmath
    //测试三角函数
    function testmath()
    {
        $k1 = ((46.5 - 45.05) / 45.05 - (45.5 - 45.05) / 45.05) * 1000 / 10;
        $k = atan($k1);//斜率=>弧度
        $a = rad2deg($k);//弧度=>角度
        echo $k . "<br> " . $a;
    }


    protected $zdf = 0.02;//涨跌幅 2%
    //http://gupiao.test/api/gupiao/isbuy
    //是否买
    //1.股价低于分时均线%1一下
    //2.分时均线角度水平
    function isbuy($list)
    {
        $open = $list[0]['close'];//开盘价
        $num = count($list);
        $pj = 0;//平均股价
        $i = 1;
        foreach ($list as &$t) {
            $pj += $t['close'];
            $t['pj'] = $pj / $i;
            $i++;
        }
        $pj = $list[$num-1]['pj']; //之前的平均股价
        $close = $list[$num-1]['close'];//最新价格
        $diefu = ($close - $pj) / $open; //跌幅 %

        //相邻5分钟的走势
        $k1 = (($list[$num-1]['pj'] - $open) / $open - ($list[$num-2]['pj'] - $open) / $open) * 1000 / 10;
        $k = atan($k1);//斜率=>弧度
        $a = rad2deg($k);//弧度=>角度

        $time = $list[$num-1]['time'];

        if ($diefu < -0.01) {
            //下跌时，均线角度小于斜向下10度 + 跌幅 > 10% ---- 买点
            if ($a > -10) {
//                echo "<br>买点：". $time." 跌幅 = " . $diefu.'  均线角度='.$a.' 价格='. $close ." <br>";
//                $b = $close + $open * 0.01;
//                echo "预卖点：". $b ."<br>";
                $this->addbuy($list[$num-1]);
            }
        } else if ($diefu > 0.01) {
            //上涨时，均线角度小于斜向上10度 + 涨幅 > 10% ---- 卖点
            if ($a < 10) {
//                echo "<br>卖点：". $time." 涨幅 = " . $diefu.'  均线角度='.$a."<br>";
//                $b = $close - $open * 0.03;
//                echo "预买点：". $b ."<br>";
                $this->addsell($list[$num-1]);
            }
        }

    }

    protected $sbase = 30;//原始股数

    function addsell($hck) {
        //确认卖出条件
        //1. 卖出价格 +- 2%范围内没有未T成功的mmlog
//        if ($this->sbase < 1) {
//            echo "无股了！";
//            return;
//        }

        $close = $hck['close'];//需要买入的价格
        $up = $close + $close * 0.01;
        $down = $close - $close * 0.01;
        $list = \app\admin\model\stock\Sslog::where('state', 0)->where("s_price < {$up}  and  s_price > {$down}" )->select();
        if ($list && $this->sbase < 4) {
            return;
        }

        $buy = new \app\admin\model\stock\Sslog();
        $buy->s_price = $close;
        $buy->riqi = $hck['riqi'];
        $buy->time = $hck['time'];
        $buy->ym_price = $close - $close * 0.01;
        $buy->save();

        $this->sbase--;

    }

    function addbuy($hck) {
        //确认买入条件
        //1. 买入价格 +- 2%范围内没有未T成功的mmlog

        $close = $hck['close'];//需要买入的价格
        $up = $close + $close * 0.01;
        $down = $close - $close * 0.01;
        $list = \app\admin\model\stock\Mmlog::where('state', 0)->where("buy_price < {$up}  and  buy_price > {$down}" )->select();
        if ($list) {
            return;
        }

        $buy = new \app\admin\model\stock\Mmlog();
        $buy->buy_price = $close;
        $buy->riqi = $hck['riqi'];
        $buy->time = $hck['time'];
        $buy->ym_price = $close + $close * 0.01;
        $buy->save();

        $this->sbase++;

    }

    //http://gupiao.test/api/gupiao/dobuy?riqi=2022-04-06
    //找到一天的买点
    //从第5个点开始看机会
    function dobuy($riqi)
    {
        $list = collection(\app\admin\model\stock\Hck::where('riqi', $riqi)->select())->toArray();

        for ($i = 0; $i < count($list); $i++) {

            $this->doT($list[$i]);
            $this->doFT($list[$i]);

            if ($i > 3) {
                $listA = [];
                $j = 0;
                foreach ($list as $t) {
                    $listA[] = $t;
                    $j++;
                    if ($j > $i) {
                        $this->isbuy($listA);
                        break;
                    }
                }
            }

        }

//        echo "<br> --ok ---";
    }

    //mmlog -- 完成正T
    function doT($hck) {
        $list = \app\admin\model\stock\Mmlog::where('state', 0)->where('ym_price', '<', $hck['close'])->where('riqi', $hck['riqi'])->select();
        foreach ($list as &$mm) {
            $mm->profit = ($hck['close'] - $mm['buy_price']) * 100;
            $mm->s_time = $hck['time'];
            $mm->r_price = $hck['close'];
            $mm->s_riqi = $hck['riqi'];
            $mm->state = 1;
            $mm->save();
            $this->sbase--;
        }
    }

    //sslog -- 完成反T
    function doFT($hck) {
        $list = \app\admin\model\stock\Sslog::where('state', 0)->where('ym_price', '>', $hck['close'])->where('riqi', $hck['riqi'])->select();
        foreach ($list as &$mm) {
            $mm->profit = ($mm['s_price'] - $hck['close']) * 100;
            $mm->b_time = $hck['time'];
            $mm->b_price = $hck['close'];
            $mm->s_riqi = $hck['riqi'];
            $mm->state = 1;
            $mm->save();
            $this->sbase++;
        }
    }

    //http://gupiao.test/api/gupiao/lllbuy?from=2021-11-15&&to=2022-04-06
    function lllbuy($from, $to)
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限

        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $riqi = $from;
        while (true) {
            $this->dobuy($riqi);
            $riqi = date("Y-m-d", strtotime("+1 days", strtotime($riqi)));
            if ($riqi > $to) {
                break;
            }
            echo "<br>".$riqi." 持仓 ". $this->sbase;
        }
        echo "<br> --ok ---";
    }

}

// select sum(profit) from fa_stock_mmlog
// select sum(profit) from fa_stock_sslog

/*
 * 按换手率低->高排序，去除涨幅过大的
 convert(int,字段名) cast(字段名 as int)

select pctChg, code, turn, date from fa_stock_k where code like '%002371' and turn <> 0
and (cast(pctChg as decimal(10,4)) > -9 and cast(pctChg as decimal(10,4)) < 9)
and date > '2019-01-14'
order by turn ASC limit 10

geini_t()
SELECT `id`,`date`,`code`,`close`,`pctChg`,`turn` FROM `fa_stock_hsl` WHERE  (  code like '%300598' and cast(turn as decimal(10,4)) > 0
and (cast(pctChg as decimal(10,4)) > -4 and cast(pctChg as decimal(10,4)) < 4)
and date > '2018-10-10' ) ORDER BY `turn` ASC LIMIT 10


UPDATE fa_stock_hsl
SET iszt=1
WHERE cast(pctChg as decimal(10,4)) > 9.9


 */
